
#include "CSubject.h"
#include <iostream>

using namespace std;


CSubject::CSubject()
{
    myData = 0;
}


CSubject::~CSubject()
{

}


bool CSubject::attach(IObserver *theObserver)
{
    list<IObserver*>::iterator iter = itsObservers.begin();
    
    for ( ; iter != itsObservers.end(); iter++)
    {
        if (*iter == theObserver)
        {
			cout << "Info from Subject: This observer is already attached" << endl;
			return false;
        }
    }
    
    itsObservers.push_back(theObserver);
	cout << "Info from Subject: Observer is now attached" << endl;
	return true;
}


void CSubject::detach(IObserver *theObserver)
{
    itsObservers.remove(theObserver);
	cout << "Info from Subject: Observer is now detached" << endl;
}


int CSubject::getData()
{
    return myData;
}


void CSubject::setData(int theData)
{
    myData = theData;
    
    notify();
}


void CSubject::notify()
{
    if (0 == itsObservers.size())
	{
		cout << "Info from Subject: Observer list is empty, notify not necessary" << endl;
		return;
	}
		
	list<IObserver*>::iterator iter = itsObservers.begin();

    for ( ; iter != itsObservers.end(); iter++)
    {
        (*iter)->update();
    }
}
